var app = getApp()
import * as Api from '../../utils/api.js'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    tabIndex: '0',
    hasGoneAway: false,
    basicMall: null,
    maintenanceUpload:false,
    haveAdd: false,
    defaultAddress: [],
    orderList: [],
    pageSize: 0,
    pageSizeRecord: 0,
    rantrecordType: 1,
    isFromSearch: false,
    isFromSearchRecord:false,
    recordList: [],
    startX: 0, //开始坐标
    startY: 0,
  },
  changeTabIndex(e) {
    this.setData({
      tabIndex: e.currentTarget.dataset.index
    })
  },
  goUserInfo() {
    if (!this.data.hasGoneAway) {
      this.setData({ hasGoneAway: true })
      wx.navigateTo({
        url: '../userinfo/userinfo',
        success: function (res) { },
        fail: function (res) { },
        complete: function (res) { },
      })
    }
  },
  goOrderDetail(e) {
    if (!this.data.hasGoneAway) {
      this.setData({ hasGoneAway: true })
      wx.navigateTo({
        url: '../../example/order_detail/order_detail?orderid=' + e.currentTarget.dataset.orderid,
        success: function (res) { },
        fail: function (res) { },
        complete: function (res) { },
      })
    }



  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

    if (app.globalData.merchant === null) {
      app.doLogin(this.onLoad, this.onShow, options);
      return
    }
    let that = this
    if (!app.globalData.merchant.basicMall){
      this.setData({
        tabIndex:'1'
      })
    }
    this.setData({
      basicMall: app.globalData.merchant.basicMall,
      maintenanceUpload: app.globalData.merchant.maintenanceUpload
    })
    if (app.globalData.userInfo) {
      that.setData({
        userInfo: app.globalData.userInfo
      })
    } else {
      wx.getUserInfo({
        withCredentials: true,
        success: function (res) {
          console.log(res)
          that.setData({
            userInfo: res.userInfo
          })

        }
      })

    }

  },
  goShip(e) {
    if (!this.data.hasGoneAway) {
      this.setData({ hasGoneAway: true })
      wx.navigateTo({
        url: '../ship/ship?orderid=' + e.currentTarget.dataset.orderid,
        success: function (res) { },
        fail: function (res) { },
        complete: function (res) { },
      })
    }
  },

  addressList() {
    if (!this.data.hasGoneAway) {
      this.setData({ hasGoneAway: true })
      wx.navigateTo({
        url: '../add_list/add_list',
      })
    }
  },


  // 删除挂单数据
  del(e) {
    console.log(e)
    let self = this
    let orderId = e.currentTarget.dataset.item.orderId
    let url = app.globalData.baseUrl1 + '/order/close'
    let list = this.data.orderList
    let index = e.currentTarget.dataset.index
    let data = {
      token: app.globalData.token,
      userId: app.globalData.userId,
      orderId: orderId
    }
    let callBack = (res) => {

      if (res == null) {
        console.log("网络请求错误1！");
        return;
      }

      if (res.data.status != 200) {
        console.log("请求数据错误1");
        wx.showToast({
          title: '请求数据错误',
        })
        return;
      }
      if (res.data.status == 200) {
          wx.showToast({
            title: '关闭成功',
          })
          list.splice(index,1)
          self.setData({
            orderList: list
          })
      }
    }
    Api.reqFormPost(url, data, callBack)
  },
  getOrderList() {
    let self = this
    let url = app.globalData.baseUrl1 + '/order/queryorder'
    let data = {
      token: app.globalData.token,
      userId: app.globalData.userId,
      // orderStatus
      page: this.data.pageSize,
      pageSize: 20
    }
    let callBack = (res) => {

      if (res == null) {

        console.log("网络请求错误1！");
        return;
      }

      if (res.data.status != 200) {
        console.log("请求数据错误1");
        return;
      }

      if (res.data.status == 200) {
        console.log(res.data)

        let goodsList = this.data.orderList

        if (res.data.data.goodsList.length != 0) {

          res.data.data.goodsList.forEach((item, index) => {
            goodsList.push(item)
          })
          this.setData({
            isFromSearch: false
          })
        } else {
          self.setData({
            rantrecordType: 2,
          });
          return
        }

        goodsList.forEach((item) => {
          item.isTouchMove = false
        })
        console.log(goodsList)
        self.setData({
          orderList: goodsList
        })


      }
    }
    Api.reqFormPost(url, data, callBack)
  },
  cancelDel(e) {
    //开始触摸时 重置所有删除
    this.data.orderList.forEach(function (v, i) {
      if (v.isTouchMove)//只操作为true的
        v.isTouchMove = false;
    })
    console.log(this.data.orderList)
    this.setData({
      orderList: this.data.orderList,
    })
  },
  //手指触摸动作开始 记录起点X坐标
  touchstart: function (e) {
    console.log(e)
    // 只有挂单的才有删除功能
    if (e.currentTarget.dataset.status != 'ORDER_ON_ACCOUNT') {
      return
    }
    this.cancelDel()
    this.setData({
      startX: e.changedTouches[0].clientX,
      startY: e.changedTouches[0].clientY,

    })

  },
  //滑动事件处理
  touchmove: function (e) {
    console.log(111)
    var that = this,
      index = e.currentTarget.dataset.index,//当前索引
      startX = that.data.startX,//开始X坐标
      startY = that.data.startY,//开始Y坐标
      touchMoveX = e.changedTouches[0].clientX,//滑动变化坐标
      touchMoveY = e.changedTouches[0].clientY,//滑动变化坐标
      //获取滑动角度
      angle = that.angle({ X: startX, Y: startY }, { X: touchMoveX, Y: touchMoveY });
    that.data.orderList.forEach(function (v, i) {
      v.isTouchMove = false
      //滑动超过30度角 return
      console.log(Math.abs(angle))
      if (Math.abs(angle) > 30) return;
      console.log(touchMoveX)
      console.log(startX)
      if (i == index) {
        if (touchMoveX > startX) //右滑
        {
          v.isTouchMove = false
        }
        else //左滑
        {
          v.isTouchMove = true
        }
      }
    })
    //更新数据
    that.setData({
      orderList: that.data.orderList,
    })
  },
  /**
   * 计算滑动角度
   * @param {Object} start 起点坐标
   * @param {Object} end 终点坐标
   */
  angle: function (start, end) {
    var _X = end.X - start.X,
      _Y = end.Y - start.Y
    //返回角度 /Math.atan()返回数字的反正切值
    return 360 * Math.atan(_Y / _X) / (2 * Math.PI);
  },


  //取地址
  getAddress() {

    let self = this
    wx.request({
      method: 'post',
      url: app.globalData.baseUrl1 + '/address/defaultaddress',
      data: {
        token: app.globalData.token,
        userId: app.globalData.userId
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded' // 默认值
      },
      success: function (res) {
        console.log(22, res.data.data)
        if (res.data.data.address) {
          self.setData({
            defaultAddress: res.data.data,
            haveAdd: true
          })
        } else {
          self.setData({
            haveAdd: false
          })
        }

      }
    })
  },
  getMaintenance() {

    let self = this
    let url = app.globalData.baseUrl1 + '/maintenance/record/listbyuser'
    let data = {
      token: app.globalData.token,
      userId: app.globalData.userId,
      page: this.data.pageSizeRecord,
      pageSize: 20
    }
    let callBack = (res) => {

      if (res == null) {

        console.log("网络请求错误1！");
        return;
      }

      if (res.data.status != 200) {
        console.log("请求数据错误1");
        return;
      }

      if (res.data.status == 200) {
        console.log('维修记录', res.data)
        res.data.data.list.forEach((item, index) => {
          item.maintenanceImg ? item.maintenanceImg = item.maintenanceImg.split(',') : ''
        })
        let recordList = this.data.recordList

        if (res.data.data.list.length != 0) {

          res.data.data.list.forEach((item, index) => {
            recordList.push(item)
          })
          this.setData({
            isFromSearchRecord: false
          })
        } else {
          console.log('来了')
          self.setData({
            rantrecordType: 2,
          });
          return
        }
        this.setData({
          recordList: recordList
        })

      }
    }
    Api.reqFormPost(url, data, callBack)


  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (app.globalData.merchant === null) {
      return
    } 
    if (app.globalData.merchant.mustLogin || app.globalData.userId === null) {
      if (app.globalData.userId === null) {
        wx.navigateTo({
          url: '/pages/core/login/login',
          success() {
            wx.showToast({
              title: '请先登陆',
              icon: 'loading',
              duration: 1000
            })
          }
        })
        return
      }
    }
    this.setData({ 
      hasGoneAway: false ,
      orderList:[],
      recordList:[]
    })

    this.getAddress();

  this.setData({
    pageSize:0
  })

  this.getOrderList();
  this.getMaintenance();



  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  searchScrollLower() {

    console.log('上拉')
    console.log(this.data.tabIndex)
    console.log(this.data.isFromSearch)
    console.log(this.data.isFromSearchRecord)
    
    if (this.data.tabIndex === '0' && this.data.isFromSearch || this.data.tabIndex === '1' && this.data.isFromSearchRecord) {
      return
    }

    this.setData({
      rantrecordType: 0,
    });

    if (this.data.tabIndex === '0') {
      this.setData({
        isFromSearch: true,
        pageSize: this.data.pageSize + 1
      })
      this.getOrderList()

    } else {
      this.setData({
        isFromSearchRecord: true,
        pageSizeRecord: this.data.pageSizeRecord + 1
      })
      this.getMaintenance()
    }


  },
  previewImage(e){
    console.log(e.currentTarget.dataset.current)
    console.log(e.currentTarget.dataset.index)

let self = this
    wx.previewImage({
      current: e.currentTarget.dataset.current, 
      urls: self.data.recordList[e.currentTarget.dataset.index].maintenanceImg
    })
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})